//
//  GlobalNoticeView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/1.
//

import UIKit

class GlobalNoticeView: UIView {
    public var text: String? {
        didSet {
            if text ?? "" == "" {
                self.isHidden = true
                self.titleLab.snp.updateConstraints { make in
                    make.height.greaterThanOrEqualTo(0)
                }
                self.layoutIfNeeded()
            }else{
                self.isHidden = false
                self.titleLab.text = text
                self.titleLab.frame.size.width = self.frame.size.width
                self.titleLab.frame.size.height = 100
                self.titleLab.sizeToFit()
                let hh = self.titleLab.frame.size.height + 20
                self.titleLab.snp.updateConstraints { make in
                    make.height.greaterThanOrEqualTo(max(44, hh))
                }
                self.layoutIfNeeded()
            }
        }
    }
    
    private var titleLab: UILabel = {
        let tempLab = UILabel()
        tempLab.textColor = Theme.titleLabColor
        tempLab.backgroundColor = UIColor.clear
        tempLab.font = UIFont.systemFont(ofSize: 14)
        tempLab.numberOfLines = 0
        tempLab.lineBreakMode = .byTruncatingTail
        tempLab.textAlignment = .left
        return tempLab
    }()
    
    private var closeBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.setup_image(image: UIImage.init(named: "notice_close"))
        return tempBtn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = true
        self.backgroundColor = UIColor.init(hex: 0xFFCC32, alpha: 0.3)
        self.addSubview(titleLab)
        self.addSubview(closeBtn)
        closeBtn.addTarget(self, action: #selector(closeBtnAction), for: .touchUpInside)
        self.addSnpLayout()
    }
    
    private func addSnpLayout(){
        titleLab.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(0)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(0)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.left.equalTo(titleLab.snp.right).offset(10)
            make.width.equalTo(20)
            make.height.equalTo(20)
            make.centerY.equalTo(titleLab.snp.centerY)
        }
    }
    
    @objc func closeBtnAction(){
        self.snp.updateConstraints { make in
            make.height.equalTo(0)
        }
        self.isHidden = true
        self.updateConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
